package com.whitedust.top50;

import java.util.ArrayList;
import java.util.List;

/**
 * @author A
 * @since 2025/11/7 12:55
 */

public class Top43 {
    public List<String> generateParenthesis(int n) {
        StringBuffer sb = new StringBuffer();
        List<String> res = new ArrayList<>();
        dfs(n, 0, 0, sb, res);
        return res;
    }

    private void dfs(int n, int left, int right, StringBuffer sb, List<String> res) {
        if (left == n && right == n) {
            res.add(sb.toString());
        }
        if (left < n) {
            sb.append("(");
            dfs(n, left + 1, right, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right < left) {
            sb.append(")");
            dfs(n, left, right + 1, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
